//
//  ShopsDetailController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/7.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage

class ShopsDetailController: BaseViewController {
    
    var merchantId : String = "-999"
    
    var dataModel : ShopsDetailModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "商家店铺"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "JDSHMenuwhiteShare_19x19_"), style: .plain, target: self, action: #selector(shareDidClick))
        
        
        weak var weakSelf = self
        
        plainTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }

        plainTableView.mj_header.beginRefreshing()
        
        plainTableView.rowHeight = UITableViewAutomaticDimension
        
        plainTableView.estimatedRowHeight = 100

        plainTableView.tableFooterView = UIView()
        
        plainTableView.backgroundColor = UIColor.viewBgGrey()
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: ShopsDetailCell.self), bundle: nil), forCellReuseIdentifier: ShopsDetailCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: ShopsDetailImageTitleCell.self), bundle: nil), forCellReuseIdentifier: ShopsDetailImageTitleCell.identifer())
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: ShopsDetailSetionCell.self), bundle: nil), forCellReuseIdentifier: ShopsDetailSetionCell.identifer())
        
        plainTableView.register(UINib(nibName: StringFromClass(classType: GameDetailTextCell.self), bundle: nil), forCellReuseIdentifier: GameDetailTextCell.identifer())
        
    }
    
    
    func shareDidClick() {
        
        weak var weakSelf = self
        
        if dataModel?.share_data?.image == nil {
            QL1("分享")
            dataModel?.share_data?.image = "http://pic.58pic.com/58pic/13/19/68/14g58PICJdQ_1024.jpg"
            
        }
        
        UMSocialUIManager.showShareMenuViewInWindow(platformSelectionBlock: { (platformType, userInfo) in
            
            switch platformType {
            case .wechatSession:
                weakSelf?.share(platformType: .wechatSession, title: weakSelf!.dataModel?.share_data?.title, desc: weakSelf!.dataModel?.share_data?.desc, image: weakSelf!.dataModel?.share_data?.image, url: weakSelf!.dataModel?.share_data?.url)
            case .wechatTimeLine:
                weakSelf?.share(platformType: .wechatTimeLine, title: weakSelf!.dataModel?.share_data?.title, desc: weakSelf!.dataModel?.share_data?.desc, image: weakSelf!.dataModel?.share_data?.image, url: weakSelf!.dataModel?.share_data?.url)
            case .QQ:
                weakSelf?.share(platformType: .QQ, title: weakSelf!.dataModel?.share_data?.title, desc: weakSelf!.dataModel?.share_data?.desc, image: weakSelf!.dataModel?.share_data?.image, url: weakSelf!.dataModel?.share_data?.url)
            case .qzone:
                weakSelf?.share(platformType: .qzone, title: weakSelf!.dataModel?.share_data?.title, desc: weakSelf!.dataModel?.share_data?.desc, image: weakSelf!.dataModel?.share_data?.image, url: weakSelf!.dataModel?.share_data?.url)
            default:
                weakSelf?.share(platformType: .wechatSession, title: weakSelf!.dataModel?.share_data?.title, desc: weakSelf!.dataModel?.share_data?.desc, image: weakSelf!.dataModel?.share_data?.image, url: weakSelf!.dataModel?.share_data?.url)
            }
            
            
            
        })
        
        
        
        
    }
    
    
    
    func share(platformType : UMSocialPlatformType,title : String?,desc : String?,image : String?,url : String?) {
        
        let sharTitle = title ?? ""
        
        let sharDesc = desc ?? ""
        
        let sharImage = image ?? "http://pic.58pic.com/58pic/13/19/68/14g58PICJdQ_1024.jpg"
        
        let sharUrl = url ?? ""
        
        let messageObj = UMSocialMessageObject.init()
        
        let shareObj = UMShareWebpageObject.shareObject(withTitle: sharTitle, descr: sharDesc, thumImage: sharImage)
        
        shareObj?.webpageUrl = sharUrl
        
        messageObj.shareObject = shareObj
        
        UMSocialManager.default().share(to: platformType, messageObject: messageObj, currentViewController: self) { (resp, error) in
            
            if error == nil{
                
                let temp = resp as? UMSocialShareResponse
                
//                QL1(temp?.message)

//                QL1(temp?.originalResponse)
                
            }
            
        }
        
    }
    
    

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        
    }
    
  
}


extension ShopsDetailController{

    func loadData(){
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["merchant_id"] = merchantId as AnyObject
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=merchant&a=detail", parameters: parmeter) {[weak self] (responseObject, error) in
            
            if error == nil {
                
                guard let temp = responseObject?["datas"]?["merchant"] as? [String : AnyObject] else{
                    
                    self!.plainTableView.mj_header.endRefreshing()
                    
                    return
                    
                }
                
                self!.dataModel = ShopsDetailModel(dic:temp )
                
                
                if self?.dataModel?.img_count == "0" {
                    
                    shopsDetailUrl = nil
                    
                    self!.plainTableView.mj_header.endRefreshing()
                    
                    self!.plainTableView.reloadData()

                
                }else{
                
                 self!.cachePictures()
                
                }
                
                
            }else{
                
                self!.plainTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
            }

    }


    }
    
    
    
    
    func cachePictures(){
        
        guard let url = URL(string: dataModel!.imgs[0]) else {
            
            self.plainTableView.mj_header.endRefreshing()
            
            
            self.plainTableView.reloadData()
            
            shopsDetailUrl = nil
            
            return
            
        }
        
        
        shopsDetailUrl = dataModel!.imgs[0]
        
        let grop = DispatchGroup()
        
        grop.enter()
        
        SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
            
            grop.leave()
            
        })
        
        
        grop.notify(queue: DispatchQueue.main) {
            
            self.plainTableView.mj_header.endRefreshing()
            
            self.plainTableView.reloadData()
            
        }
        
        
    }


}






extension ShopsDetailController{


    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModel == nil {
            
            return 0
            
        }
        
        return 1
        
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if dataModel == nil {
            return 0
            
        }
        return 8

    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var tableCell : UITableViewCell? = nil
        
        if indexPath.row == 0 {
            
            let tempCell : ShopsDetailCell =  tableView.dequeueReusableCell(withIdentifier: ShopsDetailCell.identifer()) as! ShopsDetailCell
            
            tempCell.shopName = dataModel?.merchant_name
            
            tempCell.imgs = dataModel?.imgs
            
            tableCell = tempCell
            
        } else if indexPath.row == 4 || indexPath.row == 6 {
            
            let tempCell : ShopsDetailSetionCell =  tableView.dequeueReusableCell(withIdentifier: ShopsDetailSetionCell.identifer()) as! ShopsDetailSetionCell
            
            
            tempCell.index = indexPath
            
            tableCell = tempCell
            
        }else if indexPath.row == 5 || indexPath.row == 7 {
            
            let tempCell : GameDetailTextCell =  tableView.dequeueReusableCell(withIdentifier: GameDetailTextCell.identifer()) as! GameDetailTextCell
            
            if indexPath.row == 5 {
                
                tempCell.textStr = dataModel?.merchant_introduce ?? "暂无"
                
                QL1(tempCell.textStr)

            } else {
                
                tempCell.textStr = dataModel?.merchant_class_text ?? "暂无"

            }
            
            tableCell = tempCell
            
        }else{
        
            let tempCell : ShopsDetailImageTitleCell =  tableView.dequeueReusableCell(withIdentifier: ShopsDetailImageTitleCell.identifer()) as! ShopsDetailImageTitleCell
            
            tempCell.model = dataModel
            
            tempCell.index = indexPath
            
            tableCell = tempCell

        }

        return tableCell!
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if indexPath.row == 1 {
            
        }
        
        if indexPath.row == 3{
            
            let telStr = "telprompt://\(dataModel!.merchant_mobile)"
            
            let url = URL(string: telStr)
            
            if url == nil {
                return
            }else{
                
                if  UIApplication.shared.canOpenURL(url!){
                    
                    UIApplication.shared.openURL(url!)
                    
                }
                
            }
            
            
        }
        
    }
    
  

}
